<template>
  <div class="exam-list-container">
    <h2 class="list-title">待参加考试</h2>
    <el-table :data="filteredExams" style="width: 100%">
      <el-table-column prop="name" label="考试名称" width="200" />
      <el-table-column label="所属课程" width="150">
        <template #default="{ row }">
          {{ getCategoryFromPath(row.category) }}
        </template>
      </el-table-column>
      <el-table-column label="考试时间" width="220">
        <template #default="{ row }">
          {{ formatDateTime(row.startTime) }} - {{ formatDateTime(row.endTime) }}
        </template>
      </el-table-column>
      <el-table-column label="考试时长" width="120">
        <template #default="{ row }">
          {{ calculateDuration(row.startTime, row.endTime) }}分钟
        </template>
      </el-table-column>
      <el-table-column label="考试状态" width="120">
        <template #default="{ row }">
          <el-tag :type="getStatusType(getExamStatus(row))">
            {{ getExamStatusText(getExamStatus(row)) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button
            type="primary"
            :disabled="getExamStatus(row) !== 1"
            @click="enterExam(row.id)"
          >
            {{ getExamStatus(row) === 1 ? '进入考试' : '已结束' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { reactive, computed, onMounted } from 'vue';
import { studentApi } from '@/api/studentApi'; // 引入获取考试列表的API

type ExamStatus = 0 | 1 | 2; // 0-未开始 1-进行中 2-已结束

interface ExamInfo {
  id: string;
  name: string;
  category: string; // 课程分类
  startTime: string;
  endTime: string;
  description: string;
  questions: string; // 题目列表JSON字符串
}

interface StatusMap {
  [key: number]: string;
}

export default defineComponent({
  setup() {
    const exams = reactive<ExamInfo[]>([]);

    // 从后端获取考试列表
    const fetchExamsData = async () => {
      try {
        const response = await studentApi.getExamList(); // 调用API获取考试列表
        console.log('考试列表:', response); // 调试输出API响应
        if (response.code === 200) {
          exams.splice(0, exams.length, ...response.data); // 调试输出更新后的exams数组
        } else {
          console.error('获取考试列表失败:', response.msg);
        }
      } catch (error) {
        console.error('获取考试列表失败:', error);
      }
    };

    // 格式化时间
    const formatDateTime = (timestamp: string): string => {
      const date = new Date(timestamp);
      return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`;
    };

    // 计算考试时长（分钟）
    const calculateDuration = (startTime: string, endTime: string): number => {
      const start = new Date(startTime).getTime();
      const end = new Date(endTime).getTime();
      return Math.round((end - start) / 60000);
    };

    // 获取课程分类名称
    const getCategoryFromPath = (category: string): string => {
      return category || '未知课程';
    };

    // 判断考试状态
    const getExamStatus = (exam: ExamInfo): ExamStatus => {
      const now = Date.now();
      const start = new Date(exam.startTime).getTime();
      const end = new Date(exam.endTime).getTime();

      if (now < start) return 0; // 未开始
      if (now >= start && now <= end) return 1; // 进行中
      return 2; // 已结束
    };

    // 获取考试状态文本
    const getExamStatusText = (status: ExamStatus): string => {
      const statusTextMap: StatusMap = {
        0: '未开始',
        1: '进行中',
        2: '已结束',
      };
      return statusTextMap[status] || '未知状态';
    };

    // 获取状态标签类型
    const getStatusType = (status: ExamStatus): string => {
      const statusTypeMap: StatusMap = {
        0: 'info',
        1: 'success',
        2: 'danger',
      };
      return statusTypeMap[status] || 'info';
    };

    const filteredExams = computed(() => {
      // 过滤掉已结束的考试
      return exams.filter(exam => getExamStatus(exam) !== 2);
    });

    // 进入考试
    const enterExam = (examId: string) => {
      const exam = exams.find(exam => exam.id === examId);
      if (exam) {
        // 将考试信息存储到sessionStorage中
        sessionStorage.setItem('currentExam', JSON.stringify(exam));
        // 跳转到在线测试页面
        window.location.href = '/student/exam';
      }
    };

    // 在组件挂载时获取考试列表
    onMounted(() => {
      fetchExamsData();
    });

    return {
      exams,
      filteredExams,
      formatDateTime,
      calculateDuration,
      getCategoryFromPath,
      getExamStatus,
      getExamStatusText,
      getStatusType,
      enterExam, // 返回enterExam方法
    };
  },
});
</script>

<style scoped>
.exam-list-container {
  padding: 20px;
}

.list-title {
  margin-bottom: 20px;
  color: #303133;
}
</style>
